
<template>
  <div>
    <!--批量报价-->
    <el-dialog
      :title="morePirce"
      :visible.sync="dialogVisible"
      :beforeClose="handleClose"
      width="1200px">
      <div>
        <el-form size="mini" :model="sendForm" label-width="100px" stripe ref="sendForm" :rules="rules">
          <div>
            <el-table size="mini"  :data="sendForm.goodsList" border style="width: 100%;margin:20px 0" :header-cell-style="{background:'#f8f8f9',color:'#80878f'}">
              <el-table-column
                width="150"
                fixed="left"
                align="center">
                <template slot="header" slot-scope="scope">
                  <span>商品牌号</span>
                </template>
                <template slot-scope="scope">
                  {{ scope.row.categoryName }} {{ scope.row.brandName }} {{ scope.row.goodsSn }}
                </template>
              </el-table-column>

              <el-table-column
                label="供货方"
                width="200"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.fromCompany`" :rules="rules.fromCompany">
                    <el-select style="margin-top: 10px;" v-model="scope.row.fromCompany" @change="handleWarehouse(scope.row,scope.$index)">
                     <el-option v-for = 'item in fromCompanyList'
                        :label="item.fromCompanyName"
                        :value="item.fromCompanyName"
                        :key="item.fromCompanyId">
                     </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="发货仓库"
                width="150"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.warehouseName`" :rules="rules.warehouseName">
                    <el-select style="margin-top: 10px;" v-model="scope.row.warehouseName" filterable  clearable  @change="handleSendArea(scope.row)" >
                      <el-option v-for="item in scope.row.warehouseLists" :label="item.warehouseName" :value="item.warehouseName" :key="item.warehouseId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="发货地区"
                width="200"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.sendAreaId`" :rules="rules.sendAreaId">
                    <el-cascader
                       ref="diQuIds"
                       filterable
                       clearable
                       v-model="scope.row.sendAreaId"
                       :props="{ value: 'areaId',label:'areaName',children:'children' }"
                       :options="options"
                       style="margin-top: 10px;"
                      >
                      </el-cascader>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="发货方式"
                width="100"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.sendTypes`" :rules="rules.sendTypes">
                    <el-select v-model="scope.row.sendTypes" style="width:80px;margin-top:10px;" @change="changeSendTypes(scope.row,scope.$index)">
                      <el-option  label="送到" value="送到"></el-option>
                      <el-option  label="自提" value="自提"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="结算方式"
                width="70"
                align="center">
                <template slot-scope="scope">
                  {{ scope.row.payTypes }}
                </template>
              </el-table-column>
              <el-table-column
                label="采购底价"
                width="150"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.purchasePrice`" :rules="rules.purchasePrice">
                    <el-input style="margin-top: 10px;" size="mini" type="number" v-model="scope.row.purchasePrice" clearable></el-input>
                    <div v-if="(scope.row.categoryMinPrice>0|| scope.row.categoryMaxPrice>0)&&(scope.row.purchasePrice< scope.row.categoryMinPrice || scope.row.purchasePrice > scope.row.categoryMaxPrice)" style="color: red;font-size:10px;">
                      未在产品线参考价格范围内
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="采购成本价"
                width="170"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.costPrice`" :rules="rules.costPrice">
                    <el-input style="margin-top: 10px;width:100px;" size="mini" type="number" v-model="scope.row.costPrice" clearable></el-input>
                    <div
                      v-if="scope.row.purchasePrice > 0 && scope.row.costPrice > 0"
                      style="color: red;font-size:12px;">
                      采购吨毛利：{{ scope.row.purchasePrice | fifterNumber(scope.row.costPrice) }}
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="线上平台价"
                width="170"
                align="center">
                <template slot-scope="scope">
                  <el-form-item v-if="scope.row.sendTypes=='自提'" label-width="0px" :prop="`goodsList.${scope.$index}.onlinePrice`" :rules="rules.onlinePrice">
                    <el-input style="margin-top: 10px;width:100px;" size="mini" type="number" v-model="scope.row.onlinePrice" clearable></el-input>
                    <div
                      style="color: red;font-size:12px;">
                      注意最低毛利为{{ scope.row.minProfit }}元/吨
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="有效小时数"
                width="120"
                align="center">
                <template slot-scope="scope">
                  <el-form-item v-if="scope.row.onlinePrice>0" label-width="0px" :prop="`goodsList.${scope.$index}.validHours`" :rules="rules.validHours">
                    <el-input style="margin-top: 10px;" size="mini" type="number" v-model="scope.row.validHours" clearable></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="可售库存量(吨)"
                width="120"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.stockNum`" :rules="rules.stockNum">
                    <el-input size="mini" style="margin-top: 10px;" v-model="scope.row.stockNum" clearable></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="起订量(吨)"
                width="120"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.buyMinNum`" :rules="rules.buyMinNum">
                    <el-input size="mini" style="margin-top: 10px;" v-model="scope.row.buyMinNum" clearable></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column  label="发货时间" width="150" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.sendDate`" :rules="rules.sendDate">
                    <el-date-picker
                      v-model="scope.row.sendDate"
                      style="width:120px;margin-top:10px;"
                      value-format="yyyy-MM-dd"
                      :picker-options="pickerOptions1"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="发货类型"
                width="120"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.deliveryType`" :rules="rules.deliveryType">
                    <el-select v-model="scope.row.deliveryType" style="margin-top: 10px;">
                      <el-option :disabled="scope.row.sendTypes=='自提'" label="采购发货" value="采购发货" ></el-option>
                      <el-option label="客户自提" value="客户自提"></el-option>
                      <el-option  label="公司发货" value="公司发货"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="价格类型"
                width="100"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" :prop="`goodsList.${scope.$index}.priceType`" :rules="rules.priceType">
                     <el-select v-model="scope.row.priceType" style="margin-top: 10px;">
                      <el-option label="滞销" value="滞销"></el-option>
                      <el-option label="平稳" value="平稳"></el-option>
                      <el-option label="紧俏" value="紧俏"></el-option>
                     </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                width="100"
                align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0px">
                    <el-input v-model="scope.row.priceRemark" style="margin-top: 10px;"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column  label="操作" width="100" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="delGoods(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>

      </div>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 认</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>
import {orderGoodsList,getCustomerOption} from '@/api/allInLine/partner'
import {goodsPricePublish,getFromCompanyList,warehouseList,getAreaList} from '@/api/allInLine/inquiry'
import { mapGetters } from 'vuex'
import { Message } from 'element-ui';

const defaultSendForm={
  goodsList:[],
};
const defeaultGoodListItem = {
  goodsDetailId:'',//规格商品ID
  sendAreaId:'',   //发货区域ID
  fromCompany:'',  //供货方
  warehouseName:'', //发货仓库
  stockNum: '',     //库存
  buyMinNum:'',//起订量
  payTypes:'',     //结算方式(修改时，非必填)
  purchasePrice: '',  //采购底价
  costPrice: '',//采购成本价
  onlinePrice: '',//线上平台价
  validHours:'',//有效小时数
  sendDate:'',     //发货日期
  sendTypes:'',    //发货方式(修改时，非必填)
  priceType:'',    //价格类型(滞销、紧俏、平稳)(修改时，非必填)
  priceRemark:'',    //备注(修改时，非必填)
  deliveryType:'',    //发货类型(公司发货、采购发货、客户自提)
}
export default {
  name: "index",
  data() {
    const validateStockNum = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('数量不能小于0吨'))
      }
      callback()
    };
    const validatePrice= (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('不能小于0元'))
      }
      callback()
    };
    const validateHours = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('有效小时数不得小于0小时'))
      }
      callback()
    };
    return {
      tipsFlag:false,
      dialogVisible:false,
      btnLoading:false,
      sendForm:JSON.parse(JSON.stringify(defaultSendForm)),
      rules: {
        priceType: [{ required: true, message: '请选择价格类型', trigger: 'change' }],
        sendDate:[{required:true,message:'请选择发货日期',trigger:'change'}],
        purchasePrice: [
          { required: true, message: '请填写采购底价', trigger: 'blur' },
          {validator:validatePrice,trigger: "blur"}
        ],
        costPrice: [
          { required: true, message: '请填写采购成本价', trigger: 'blur' },
          {validator:validatePrice,trigger: "blur"}
        ],
        onlinePrice: [
          {validator:validatePrice,trigger: "blur"}
        ],
        validHours: [
          { required: true, message: "请输入有效小时数", trigger: "blur" },
          {validator:validateHours,trigger: "blur"}
        ],
        stockNum: [
          { required: true, message: '请填写可售库存量', trigger: 'blur' },
          {validator:validateStockNum,trigger: "blur"}
        ],
        buyMinNum: [
          {validator:validateStockNum,trigger: "blur"}
        ],
        sendTypes:[{required:true,message:'请选择发货方式',trigger:'change'}],
        sendAreaId:[{required:true,message:'请选择发货地',trigger:'change'}],
        deliveryType: [{ required: true, message: '请选择发货类型', trigger: 'change' }],
      },
      querySearchList:[],
      goodsList:[],
      diQuIds:[],
      options:[],
      morePirce:'',
      fromCompanyList:[],
      warehouseLists:[],
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now()  - 8.64e7;
        },
      },
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components : {

  },
  created() {

  },
  filters: {
    fifterNumber(val1, val2) {
      let newval1 = val1 ? val1 : 0;
      let newval2 = val2 ? val2 : 0;
      return (newval1 - newval2).toFixed(2)
    }
  },
  methods:{
    //客户名称输入匹配
    querySearch(queryString){
      if(queryString && queryString!= ''){
        getCustomerOption({keywords:queryString,tab:'my'}).then((res)=>{
          this.querySearchList = res;
        })
      }
    },

    async handleWarehouse(val,index){
      val.warehouseName = ''
      val.sendAreaId = ''
      await warehouseList({fromCompany:val.fromCompany}).then(res=>{
         let c = JSON.parse(JSON.stringify(this.sendForm.goodsList[index]))
         c.warehouseLists = res.list
         this.sendForm.goodsList.splice(index,1,c,)
       })
    },
    handleSendArea(val){
      val.sendAreaId =[]
      const data =  val.warehouseLists.filter(item=>{
      return   item.warehouseName == val.warehouseName})
      if(data.length>0){
        val.sendAreaId = [data[0].provinceId,data[0].cityId,data[0].areaId]
      }
    },
    // 发货公司列表
    fromCompanysList(){
      getFromCompanyList().then(res=>{
        this.fromCompanyList = res
      })
    },

    //显示询价
    showPop(item, type) {
      this.dialogVisible = true;
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
      this.fromCompanysList();
      this.getAddressListData();
      if (type == 'goods') {
        this.morePirce = '批量报价'
        item.forEach(async item => {
          // 获取供货方列表
          await warehouseList({ fromCompany: item.fromCompany }).then(res => {
            item['warehouseLists'] = res.list
          });
          item.warehouseName = item.warehouseName ? item.warehouseName : '';
          item.warehouseId = item.warehouseId ? item.warehouseId : '';
          item['sendAreaId'] = item.provinceId ? [item.provinceId, item.cityId, item.areaId] : '';
          item.stockNum = item.goodsStock ? item.goodsStock : '';
          item.buyMinNum = item.buyMinNum ? item.buyMinNum : '';
          item.onlinePrice = item.onlinePrice ? item.onlinePrice : '';
          item.minProfit = item.minProfit ? item.minProfit : '';//最低毛利
          if(item.sendTypes == '送到'){
            item.deliveryType = '采购发货'
          };
          const dataItem = JSON.parse(JSON.stringify(item));
          this.sendForm.goodsList.push(dataItem);
       })
      }else if (type == 'create'){
        this.morePirce = '批量复制报价'
        item.forEach(async el =>{
            const dataItem = JSON.parse(JSON.stringify(defeaultGoodListItem))
            dataItem.brandName = el.brandName
            dataItem.categoryName = el.categoryName
            dataItem.fromCompany = el.fromCompany
            dataItem.goodsDetailId = el.goodsDetailId
            dataItem.goodsSn = el.goodsSn
            dataItem.payTypes = el.payTypes
            dataItem.goodsSn = el.goodsSn
            dataItem.sendTypes = el.sendTypes
            dataItem.purchasePrice = el.purchasePrice
            dataItem.costPrice = el.costPrice
            dataItem.onlinePrice = el.onlinePrice ? el.onlinePrice : ''
            dataItem.validHours = el.validHours ? el.validHours : ''
            dataItem.stockNum = el.stockNum
            dataItem.buyMinNum = el.buyMinNum
            // dataItem.sendDate = el.sendDate
            dataItem.priceRemark = el.priceRemark
            dataItem.deliveryType = el.deliveryType
            dataItem.priceType = el.priceType
            await warehouseList({ fromCompany: el.fromCompany }).then(res => {
              dataItem['warehouseLists'] = res.list
              let i = res.list.findIndex((item) => {
                return item.warehouseName == el.warehouseName;
              })
              let sendAreaList = res.list[i] ? res.list[i] : [];
              dataItem.sendAreaId = sendAreaList.provinceId ? [sendAreaList.provinceId, sendAreaList.cityId, sendAreaList.areaId] : '';
            });
          dataItem.warehouseName = el.warehouseName ? el.warehouseName : '';
          dataItem.warehouseId = el.warehouseId ? el.warehouseId : '';
          dataItem.minProfit = el.minProfit ? el.minProfit : '';//最低毛利
          this.sendForm.goodsList.push(dataItem)
        })
      }
    },

    //关闭询价
    handleClose(){
      this.sendForm=JSON.parse(JSON.stringify(defaultSendForm))
      this.dialogVisible = false;
    },

    //确认
    handleConfirm(){
      this.$refs.sendForm.validate(valid=>{
      if(valid){
          this.btnLoading = true
        const data = JSON.parse(JSON.stringify(this.sendForm))
          data.goodsList.forEach(item=>{
            item.sendAreaId = item.sendAreaId.length>0?item.sendAreaId[item.sendAreaId.length - 1]:''
            delete item.warehouseLists
            delete item.sendArea
            delete item.priceTime
            delete item.pOId
            delete item.normProfit
            delete item.minProfit
            delete item.materialId
            delete item.inquirySort
            delete item.goodsWeight
            delete item.goodsStock
            delete item.goodsSn
            delete item.goodsName
            delete item.goodsId
            delete item.createUserName
            delete item.chargeUserName
            if (item.purchasePrice - item.costPrice <= -200) {
              this.tipsFlag=true
            }
          })
        goodsPricePublish(data).then(res => {
          if (res) {
            Message.success('报价成功')
            if (this.tipsFlag) {
              this.$alert('您的报价中存在毛利过低', '提示', {
                confirmButtonText: '关闭',
              });
            }
            this.btnLoading = false
            this.dialogVisible = false;
            this.$emit('update')
            this.$refs.sendForm.resetFeilds()
            this.sendForm = JSON.parse(JSON.stringify(defaultSendForm))
          }
      }).catch(err=>{
          this.btnLoading = false
      })
       }else{
        this.$message.error('必填验证未通过')
      }
      })
    },
    //获取省市区列表
    getAddressListData(){
      getAreaList().then((res)=>{
        this.options = res;
      })
    },
    //删除商品
    delGoods(index){
      this.sendForm.goodsList.splice(index,1)
    },
    //增加商品
    addGoods(){
      this.sendForm.goodLineList.push(JSON.parse(JSON.stringify(defeaultGoodLineItem)))
    },

    // 改变发货方式
    changeSendTypes(data,index){
      const el = JSON.parse(JSON.stringify(data))
      if(el.sendTypes == '自提'){
        el.deliveryType = ''
      }else if(el.sendTypes == '送到'){
        el.deliveryType = '采购发货'
      }
      this.sendForm.goodsList.splice(index,1,el)
    }
  },
}
</script>

<style  lang="scss" scoped>


</style>

